package api

import (
	_ "jtvss/api/controller"
	_ "jtvss/api/operation"
	_ "jtvss/api/system"
	"jtvss/configs"
	"jtvss/middleware"
	"jtvss/pkg/ctx"
	"jtvss/util"
	"jtvss/views"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

type Options struct {
	Timeout int
	Port    int
	Root    string
	Public  string
}

// New
func Run() error {
	var opts Options
	if err := configs.GViper.UnmarshalKey("serve", &opts); err != nil {
		return err
	}
	engine := gin.Default()
	// r.Use(middleware.LoadTLS()) // https
	engine.Use(middleware.Cors()) // 跨域
	views.Static(engine, opts.Root)
	r := engine.Group(opts.Root + "/api")
	r.StaticFS("/public", http.Dir(util.Public.Abs(opts.Public)))
	ctx.Use(r, middleware.UseJWTAuth(r.Group("")), middleware.UseTokenAuth(r.Group("")))
	s := ctx.ListenAndServe(engine, opts.Port, opts.Timeout)
	log.Printf("%s serve start at %s", configs.AppName, s.Addr)
	return nil
}

func Shutdown() error {
	return ctx.Release()
}
